﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using OnlineVideos;
using OnlineVideos.Data;
using Common.Library;
using System.Windows.Media;
using AdRotator;
using System.Windows.Input;
using HtmlAgilityPack;

namespace OnlineMovies.Views
{
    public partial class LinksFromOnline : PhoneApplicationPage
    {
       
        string uri = string.Empty;
        public IDictionary<string, string[]> MusicDic = new Dictionary<string, string[]>();
        Stack<Uri> history = new Stack<Uri>();
        string absoluteuri = string.Empty;
        bool NavigatingBack = false;
        string language = string.Empty;
        string absolutepath = string.Empty;
        List<AutoComplete> v = new List<AutoComplete>();
     

        public string navigatingURL;
        public string loadedURL;
        public LinksFromOnline()
        {
            InitializeComponent();

            this.Loaded += LinksFromOnline_Loaded;

            this.OrientationChanged += new EventHandler<OrientationChangedEventArgs>(BrowserPage_OrientationChanged);

        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.EndTimedEvent("LinksFromOnline Page");
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedFrom Method In LinksFromOnline.cs file.", ex);
            }
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
               
                    FlurryWP8SDK.Api.LogPageView();
              
                if (NavigationContext.QueryString["language"].ToString() != null)
                {
                    language = NavigationContext.QueryString["language"].ToString();
                }
                if (e.NavigationMode != NavigationMode.Back)
                {
                    MusicDic.Add("Hindi", new string[] {"http://hindisongss.blogspot.in/2009/04/hindi-movies-list.html","http://www.bollygold.com/mp3s/Bollywood/",  "http://www.songslover.pk/bollywood/",  "http://webmusic.in/hindi.html", "http://www.pakheaven.com/music/indian-movies/","http://songs2hit.blogspot.in/"});
                    MusicDic.Add("Telugu", new string[] { "http://mp3songsdownloadmp3.blogspot.in/search?updated-min=2012-01-01T00:00:00-08:00&updated-max=2013-01-01T00:00:00-08:00&max-results=50", "http://www.machomusiq.com/search/label/Telugu%20-%20MP3" });
                    MusicDic.Add("Tamil", new string[] {"http://tamilkey.ws/category/download-tamil-movie-latest-mp3-songs","http://tamilmoviesongs.net/"});
                    //tamil:"http://www.starmusiq.com/mp3database.asp";
                }
                if (e.NavigationMode == NavigationMode.Back)
                {
                    NavigationService.GoBack();
                }
            }
            catch(Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo Method In LinksFromOnline.cs file.", ex);
            }
        }
        void LinksFromOnline_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.LogEvent("LinksFromOnline Page", true);
                if (Constants.Linkstype == "Movies" || Constants.Linkstype == "Songs")
                    webBrowser1.Navigate(new Uri("http://www.youtube.com", UriKind.RelativeOrAbsolute), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");
                else if (Constants.Linkstype == "Audio")
                {


                    txtlink.ItemsSource = MusicDic.Where(i => i.Key == language).FirstOrDefault().Value;

                }
                //if (Constants.Linkstype == "Audio")
                //    txtlink.IsEnabled = true;
                //else
                //    txtlink.IsEnabled = false;
                Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
                AdRotatorControl Adc = frameBorder.FindName("AdRotatorWin8") as AdRotatorControl;
                Adc.IsAdRotatorEnabled = false;
                Adc.Visibility = Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LinksFromOnline_Loaded Method In LinksFromOnline.cs file.", ex);
            }
        }




        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                Constants.DownloadTimer.Start();
                base.OnBackKeyPress(e);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in OnBackKeyPress Method In LinksFromOnline.cs file.", ex);
            }
        }

        void BrowserPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
        {
            try
            {
                if (e.Orientation == PageOrientation.Portrait || e.Orientation == PageOrientation.PortraitDown || e.Orientation == PageOrientation.PortraitUp)
                {
                    webBrowser1.Height = 740;
                    webBrowser1.Width = 480;
                    txtlink.Width = 410;
                    txtlink.Margin = new Thickness(0, -5, 0, 0);
                    imgfldr.Width = 90;
                    imgfldr.Margin = new Thickness(0, -4, 0, 0);

                }
                else
                {
                    webBrowser1.Height = 420;
                    webBrowser1.Width = 800;
                    txtlink.Margin = new Thickness(0, -5, 0, 0);
                    txtlink.Width = 730;
                    imgfldr.Margin = new Thickness(-20, -5, 0, 0);
                    imgfldr.Width = 100;

                }

            }


            catch (Exception ex)
            {
                string excepmess = "Exception in BrowserPage_OrientationChanged Method In browserpage file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
                Exceptions.SaveOrSendExceptions("Exception in BrowserPage_OrientationChanged Method In LinksFromOnline.cs file.", ex);
            }
        }



        private void webBrowser1_Navigating(object sender, NavigatingEventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(e.Uri.DnsSafeHost) && !e.Uri.ToString().Contains("adserver") && !e.Uri.ToString().Contains("out.popads"))
                {
                    if (!e.Uri.ToString().Contains("http"))
                    {
                        e.Cancel = true;
                        MessageBoxResult result = MessageBox.Show("cannot add links from this site", "", MessageBoxButton.OK);
                        if (result == MessageBoxResult.OK)
                        {
                            NavigationService.GoBack();
                        }

                    }
                    else
                    {
                        if (NavigatingBack == false)
                        {
                            e.Cancel = true;
                            webBrowser1.Navigate(new Uri(e.Uri.ToString(), UriKind.RelativeOrAbsolute), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");
                            imgfldr.Visibility = Visibility.Visible;
                            navigatingURL = e.Uri.ToString();
                            txtlink.Text = navigatingURL;
                            AppSettings.NavigationUrl = navigatingURL;
                            NavigatingBack = true;
                        }
                        else
                        {
                            NavigatingBack = false;
                        }
                    }
                }
                else
                    e.Cancel = true;

            }

            catch (Exception ex)
            {
                string excepmess = "Exception in webBrowser1_Navigating Method In browserpage file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
                Exceptions.SaveOrSendExceptions("Exception in webBrowser1_Navigating Method In LinksFromOnline.cs file.", ex);
            }
        }

        private void webBrowser1_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
               
                NavigatingBack = false;
                performanceProgressBar.IsIndeterminate = false;
                txtmessage.Visibility = Visibility.Collapsed;
                txtlink.Margin = new Thickness(20, 0, 0, 0);
                txtlink.Width = 400;
                imgfldr.Visibility = Visibility.Visible;
                loadedURL = e.Uri.ToString();

            }


            catch (Exception ex)
            {
                string excepmess = "Exception in webBrowser1_LoadCompleted Method In browserpage file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
                Exceptions.SaveOrSendExceptions("Exception in webBrowser1_LoadCompleted Method In LinksFromOnline.cs file.", ex);
            }
        }



        private void txtlink_KeyUp(object sender, KeyEventArgs e)
        {

            try
            {

                if (txtlink.Text != "")
                {
                    txtmessage.Visibility = Visibility.Collapsed;
                    if (e.Key == Key.Enter)
                    {
                        if (!txtlink.Text.ToLower().StartsWith("http://"))
                        {
                            if (txtlink.Text.ToLower().Contains("www."))
                                txtlink.Text = "http://" + txtlink.Text;
                            else
                                txtlink.Text = "http://www." + txtlink.Text;
                        }
                        performanceProgressBar.IsIndeterminate = true;
                        webBrowser1.Navigate(new Uri(txtlink.Text, UriKind.RelativeOrAbsolute), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");

                    }

                }
                else
                {
                    txtmessage.Visibility = Visibility.Visible;
                }
            }

            catch (Exception ex)
            {
                string excepmess = "Exception in txtlink_KeyUp Method In browserpage file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
                Exceptions.SaveOrSendExceptions("Exception in txtlink_KeyUp Method In LinksFromOnline.cs file.", ex);
            }
        }



        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                AppSettings.htmltext = webBrowser1.SaveToString();
                if (Constants.Linkstype == "Audio")
                    audiolinks();
                NavigationService.Navigate(new Uri("/Views/OnlineLinks.xaml", UriKind.Relative));
            }
            catch(Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in Image_MouseLeftButtonDown Method In LinksFromOnline.cs file.", ex);
            }
        }
        public void audiolinks()
        {
            try
            {
                Constants.AudiosLinks.Clear();
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(AppSettings.htmltext);
                if (Constants.NavigatedUri.Contains("songsaround.com"))
                {
                    foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//a[@href]"))
                    {
                        if (node.Attributes["href"].Value.EndsWith(".mp3"))
                        {
                            Constants.AudiosLinks.Add(node.Attributes["href"].Value, node.Attributes["href"].Value.Substring(node.Attributes["href"].Value.LastIndexOf('/') + 1, (node.Attributes["href"].Value.IndexOf(".mp3")) - (node.Attributes["href"].Value.LastIndexOf('/'))));
                        }
                    }
                }

                else
                {
                    foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//a[@href]"))
                    {
                         string link =string.Empty;
                        if (node.Attributes["href"].Value.EndsWith(".mp3"))
                        {
                            if (node.Attributes["href"].Value.StartsWith("http"))
                            {
                                link=node.Attributes["href"].Value;
                            }
                            else
                            {
                              link ="http://"+ absolutepath + node.Attributes["href"].Value;
                            }
                            if(!Constants.AudiosLinks.ContainsKey(link))
                            Constants.AudiosLinks.Add(link, node.InnerText);
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in audiolinks Method In LinksFromOnline.cs file.", ex);
                MessageBoxResult result = MessageBox.Show("cannot add links from this site", "", MessageBoxButton.OK);
                if (result == MessageBoxResult.OK)
                {
                    NavigationService.GoBack();
                }
              
            }

        }
        private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                Constants.NavigatedUri = e.Uri.AbsoluteUri;
                 absolutepath = e.Uri.Host.ToString() + e.Uri.AbsolutePath.ToString().Substring(0, e.Uri.AbsolutePath.ToString().LastIndexOf('/') + 1);
            }
            catch(Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in webBrowser1_Navigated Method In LinksFromOnline.cs file.", ex);
            }
        }

        private void txtlink_MouseEnter_1(object sender, MouseEventArgs e)
        {


        }



    }
}